package com.mymarkdown.app.fx.event.hander.impl;

import com.mymarkdown.app.common.constant.Constant;
import com.mymarkdown.app.fx.annotation.KeyWord;
import com.mymarkdown.app.fx.enums.FxEventEnum;
import com.mymarkdown.app.fx.event.hander.KeyWordHandler;
import com.mymarkdown.app.fx.event.hander.MenuHandler;
import com.mymarkdown.app.fx.event.model.FxEvent;
import com.mymarkdown.app.interfaces.UserInfoService;
import com.mymarkdown.app.util.*;
import com.mymarkdown.app.websocket.enums.MessageTypeEnum;
import com.mymarkdown.app.websocket.interfaces.WebSocketSendMessage;
import com.mymarkdown.app.websocket.message.MessagePojo;
import javafx.scene.web.WebEngine;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;

/**
 * @author zenglun
 * @date 2021/12/7 3:53 下午
 * @description: 导出为pdf文档处理
 */
@Slf4j
@KeyWord(FxEventEnum.EXPORT_MD_PDF)
@Component
public class ExportMdPdfMenuHandlerImpl implements MenuHandler, KeyWordHandler {

    @Autowired
    private WebSocketSendMessage webSocketSendMessage;

    @Autowired
    private UserInfoService userInfoService;


    @Override
    public void handler(WebEngine engine, FxEvent event) {
        //下发指令给客户端,获取HTML,获取完成之后，转换为
        webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.GET_MD_TO_HTML.getMessageType()));

        //弹出对话框要用户进行选择，
        FileChooserUtil.showSaveDialog(file -> {

            BlockingQueue<File> operationMdPdfFile = userInfoService.getOperationMdPdfFile();

            try {
                File operationPdfFile = operationMdPdfFile.peek();

                if (!Objects.isNull(operationPdfFile)) {
                    operationMdPdfFile.clear();
                }

                operationMdPdfFile.put(file);
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.error("[ExportMdPdfMenuHandlerImpl]---[handler],保存当前要保存的PDF文档发生中断,异常信息为:{}", e);
            }
        }, "pdf", "*.pdf");

        //开启一个线程保存数据
        ThreadPool.getInstant().commit(() -> {
            //获取操作的html内容
            try {
                BlockingQueue<String> operationMdHTML = userInfoService.getOperationMdHTML();

                String html = operationMdHTML.take();

                //获取当前 将HTML内容转换为PDF
                BlockingQueue<File> operationMdPdfFile = userInfoService.getOperationMdPdfFile();

                //得到相应

                File pdfDet = operationMdPdfFile.take();

                //读取模板字符串

                html = TemplateHtmlUtil.getSelf().getTemplateStr() + html + "</div></body></html>";

                //创建临时文件夹
                // 此处需要修改代码，将其改为可配置性的代码
                File tempImage = new File(Constant.AllFilePath.SVG_IMAGE_TEMP_PATH);
                if (!tempImage.exists()) {
                    tempImage.mkdirs();
                }

                //解析HTML里面的内容将其尺量图替换为相应图片,同时创建一个临时文件夹用于存放生成的图片
                //然后将生成的html在进行转换,得到PDF文档
                Document parse = Jsoup.parse(html);
                
                //开始找寻所有的image图片
                //如果image的src属性不是以http://开头则，
                FileUtil.replaceLocalFileToRemote(parse);
                
                //替换流程图图片,将尺量图替换为png图片，解决pdf文档不显示尺量图问题
                Arrays.stream(Constant.SVG_ARR).forEach(svg -> JsoupUtil.svgToImg(parse.select(svg), tempImage.getPath()));

                //获取解析后的html
                //处理本地HTML文件兼容以前的文件

                //开始转换
                HtmlToPdfUtil.HTMLContentToPdf(parse.html(), pdfDet.getPath());

                //转换成功之后下发通知告诉用户已经转换完毕
                webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.TISP_MSG.getMessageType()).setBody("导出成功!"));
            } catch (IOException e) {
                e.printStackTrace();
                log.error("[ExportMdPdfMenuHandlerImpl]---[handler],Html转pdf失败,异常信息为:{}", e);
                webSocketSendMessage.sendMessage(MessagePojo.empty().setMessageType(MessageTypeEnum.TISP_MSG.getMessageType()).setBody("导出PDF文档失败!"));
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.error("[ExportMdPdfMenuHandlerImpl]---[handler],等待客户端上传HTML发生中断,异常信息为:{}", e);
            }
        });
    }

    @Override
    public boolean afterHandler(WebEngine engine, FxEvent event) {
        return true;
    }

    @Override
    public void beforeHandler(WebEngine engine, FxEvent event) {

    }
}
